package org.thanos.demo.http.session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thanos.demo.http.cache.SessionCache;

import java.util.Optional;
import java.util.UUID;

@Service("sessionManageService")
public class SessionManageServiceImpl implements SessionManageService {

    @Autowired
    private SessionCache<String, SessionEntity> sessionCache;

    @Override
    public Optional<String> createToken(int id, String loginId) {
        String uuid = UUID.randomUUID().toString();
        SessionEntity entity = new SessionEntity();
        entity.setId(id);
        entity.setLoginId(loginId);
        entity.setTimestamp(System.currentTimeMillis());
        entity.setUuid(uuid);
        sessionCache.saveSession(uuid, entity);
        return Optional.of(uuid);
    }

    @Override
    public void removeToken(String token) {
        sessionCache.removeSession(token);
    }

    @Override
    public Optional<SessionEntity> verifyToken(String token) {
        SessionEntity entity = sessionCache.readSession(token);
        Optional<SessionEntity> entityOptional = Optional.ofNullable(entity);
        if (entityOptional.isPresent()) {
            sessionCache.saveSession(token, entity);
        }
        return entityOptional;
    }
}
